import { HttpService } from 'src/app/shared/service/http.service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { link } from 'fs';
import { PageModalService } from './../../shared/service/page-modal-service';
import { Component, Input, OnInit } from '@angular/core';
import { EventService } from '../../shared/service/event.service';

@Component({
  selector: 'app-classification',
  templateUrl: './classification.component.html',
  styleUrls: ['./classification.component.scss'],
})
export class ClassificationComponent implements OnInit {
  @Input() tagData: any;
  constructor(
    private pageModalService: PageModalService,
    private appGlobalService: AppGlobalService,
    private eventService: EventService,
    private httpService: HttpService
  ) { }

  newStyleMainBoxCssStyle: any;
  singleRowBoxCssStyle: any;
  singleRowTitleCssStyle: any;
  singleItemBoxCssStyle: any;
  subDataBoxCssStyle: any;
  subDataImgBoxCssStyle: any;
  subDataLabelCssStyle: any;

  pageNo: any = 1;
  params: any;
  sessionId = localStorage.getItem("sessionId");

  setCssStyleByLinkParams(linkParams) {

    if (linkParams !== undefined) {
      if (linkParams.newStyleMainBoxCssStyle !== undefined) {
        this.newStyleMainBoxCssStyle = linkParams.newStyleMainBoxCssStyle;
      }
      if (linkParams.singleRowBoxCssStyle !== undefined) {
        this.singleRowBoxCssStyle = linkParams.singleRowBoxCssStyle;
      }
      if (linkParams.singleRowTitleCssStyle !== undefined) {
        this.singleRowTitleCssStyle = linkParams.singleRowTitleCssStyle;
      }
      if (linkParams.singleItemBoxCssStyle !== undefined) {
        this.singleItemBoxCssStyle = linkParams.singleItemBoxCssStyle;
      }
      if (linkParams.subDataBoxCssStyle !== undefined) {
        this.subDataBoxCssStyle = linkParams.subDataBoxCssStyle;
      }
      if (linkParams.subDataImgBoxCssStyle !== undefined) {
        this.subDataImgBoxCssStyle = linkParams.subDataImgBoxCssStyle;
      }
      if (linkParams.subDataLabelCssStyle !== undefined) {
        this.subDataLabelCssStyle = linkParams.subDataLabelCssStyle;
      }
    }
  }

  ngOnInit() {

    let tempLinkParams;
    if (this.tagData.data
      && this.tagData.data.data
      && this.tagData.data.data.children
      && this.tagData.data.data.children.length > 0
      && this.tagData.data.data.children[0].link) {
      tempLinkParams = this.tagData.data.data.children[0].link.params;
      this.setCssStyleByLinkParams(tempLinkParams);
    } else {
      if (this.tagData.data &&
        this.tagData.data.link &&
        this.tagData.data.link.params) {
        this.setCssStyleByLinkParams(this.tagData.data.link.params);
      }
    }

    if (this.tagData.data && this.tagData.data.data && this.tagData.data.data.length > 0) {
      this.tagData.data.data[0].open = true;
      this.tagData.current = this.tagData.data.data[0];
      this.tagData.data.data.forEach(element => {
        if (element.checked) {
          this.tagData.data.data[0].open = false;
          element.open = true;
          this.tagData.current = element;
        }
      });
    }

    if (this.tagData && this.tagData.name === 'supermarketProducts') {
      this.appGlobalService.settleCartIds = new Set();

      // 2024.04.11 新增事件用于
      // refreshCartInfo
      const singleDataTagName = 'refreshCartInfo';
      console.log('singleDataTagName=', singleDataTagName);
      if (this.eventService.eventEmit.listenerCount(singleDataTagName) > 0) {
        this.eventService.eventEmit.removeListener(singleDataTagName);
      }
      this.eventService.eventEmit.on(singleDataTagName, (res) => {
        // this.updateSingleData(res);
        this.refreshCartInfo(res);
      });
      for (let index = 0; index < this.tagData.classData.length; index++) {
        const element = this.tagData.classData[index];
        if (element.checked) {
          element.open = true;
          this.params = element.submit; // 2.2.19 版本新增
          this.tagData.current = element;
        } else {
          element.open = false;
        }
      }
    }
  }

  // 更新购物车数量与金额
  refreshCartInfo(res) {

    console.log('refreshCartInfo', res);

    // 更新 当前商品的buyCount
    if (this.tagData.listData && this.tagData.listData.length > 0) {
      for (let index = 0; index < this.tagData.listData.length; index++) {
        const element = this.tagData.listData[index];
        if (element.shop_goods_id === res.params.goods_id) {
          if (res.subType !== undefined) {
            element.buyCount = parseInt(res.params.count);
          } else {
            element.buyCount = parseInt(element.buyCount) + parseInt(res.params.count);
          }

          break;
        }
      }
    }
    if (res.subType === undefined) { // 从购物车弹窗发送的购物车Id shopping-car event.emit
      const result = res.data.eventResult.split(',');
      const cartId = result[1];
      const count = result[0];
      //res money
      const money = parseInt(res.params.count) * res.params.price;
      this.pageModalService.chatService.setCartItemCount(count,true);
      this.appGlobalService.settleCartPrice = Math.fround(this.appGlobalService.settleCartPrice * 100) / 100 + money;
      this.appGlobalService.settleCartPrice = Math.fround(this.appGlobalService.settleCartPrice * 100) / 100;
      this.appGlobalService.settleCartIds.add(cartId);
    }

  }

  addToCart(tag) {
    // console.log('添加到购物车', tag);
    // // 跳转页面选择规格

    // const obj = {
    //   "link": {
    //     "label": "",
    //     "type": "pageModal",
    //     "params": {
    //       "store_id": "656ed68cf8f13468bd8f8d9c",
    //       "base_info_id": "656ed68cf8f13468bd8f8d9d",
    //       "btnCssStyle": "padding: unset;margin-bottom: unset;height: 1.75rem;line-height: unset;align-items: center;display: flex;width: 4.5rem;justify-content: center;margin-top: 0.5rem;background: linear-gradient(135deg, #FFDE3B 0%, #FFC933 100%);border:unset;font-size: 0.75rem;font-weight: bold;color: #222222;",
    //       "modalCss": "auto-modal",
    //       "cssStyle": "display: flex;flex-direction: column;justify-content: space-between;height: 60vh;width: 100%;",
    //       "id": "64edbdace308d13e945a3c5c",
    //       "isRepeat": "true",
    //       "type": "1",
    //       "customer": "1"
    //     },
    //     "target": "195828"
    //   }
    // };
    // this.pageModalService.openPage(obj.link);


    if (tag && tag.addModel && tag.addModel.link) {
      this.pageModalService.openPage(tag.addModel.link);
    }



  }

  gotoDetail(ev, link) {

    if (ev) {
      ev.stopPropagation();
    }

    this.pageModalService.openPage(link);
  }





  // 左边大类点击 传type表示 商品分类的点击事件
  itemLeftClick(it, type?) {

    if (type !== undefined) {
      this.tagData.classData.forEach(element => {
        element.open = false;
      });
    } else {
      this.tagData.data.data.forEach(element => {
        element.open = false;
      });
    }
    it.open = true;
    this.tagData.current = it;

    if (type !== undefined) {
      // 2.2.19 新增submit请求
      it.submit.content['pageNo'] = 1;
      this.pageNo = 1;
      this.params = it.submit;
      const params = {
        content: it.submit.content,
        id: it.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        console.log('submit', res);
        if (res.success) {
          this.tagData.listData = res.data.listData;
        } else {
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
      });
    }



  }
  tagClick(tag) {
    if (this.tagData.data &&
      this.tagData.data.link &&
      this.tagData.data.link.params &&
      this.tagData.data.link.params.selectItemBack &&
      this.tagData.data.link.params.selectItemBack === "true") {
      this.eventService.eventEmit.emit('selectService', tag);
      this.appGlobalService.goBack();
      this.appGlobalService.popTarget();
    } else
      if (this.tagData.data && this.tagData.data.link && this.tagData.data.formKey) {
        if (this.tagData.data.link.params) {
          this.tagData.data.link.params[this.tagData.data.formKey] = tag.code;
        } else {
          this.tagData.data.link.params = { [this.tagData.data.formKey]: tag.code };
        }
        if (this.tagData.data.link.type === undefined) {
          tag.link.type = 'page'; // 防止后端返回异常数据
        }
        this.pageModalService.openPage(this.tagData.data.link);
      } else if (this.tagData.data && tag && tag.link) {
        if (tag.link.type === undefined) {
          tag.link.type = 'page'; // 防止后端返回异常数据
        }
        if (tag.link.params) {
          tag.link.params[this.tagData.data.formKey] = tag.code;
        } else {
          tag.link.params = { [this.tagData.data.formKey]: tag.code };

        }
        this.pageModalService.openPage(tag.link);

      } else if (this.tagData.data && this.tagData.data.submit && this.tagData.data.submit.params
        && this.tagData.data.submit.params.code !== undefined && this.tagData.data.submit.params.parent_id !== undefined) {
        this.tagData.data.submit.params.code = tag.code;
        this.tagData.data.submit.params.parent_id = this.tagData.current.code;

        const params = {
          content: this.tagData.data.submit.params,
          id: this.tagData.data.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };

        this.httpService.post("application/submit", params, res => {

          if (res.success && res.target) {

            if (res.data && res.data.eventResult && res.params && res.params.eventResult) {
              res.params[res.params.eventResult] = res.data.eventResult;
            }
            let type = res.type ? res.type : 'page';
            if (res.skip === 1) {
              type = 'page';
            } else if (res.skip === 4) {
              type = 'pageModal';
            }
            // tslint:disable-next-line:no-shadowed-variable
            const link = {
              type,
              target: res.target,
              params: res.params ? res.params : {}
            };
            this.pageModalService.openPage(link);

          }
        });
      } else {
        this.pageModalService.openPage(tag.link);
      }

  }

  // 记载更多
  loadData(event) {
    if (event) {
      event.stopPropagation();
    }
    setTimeout(() => {
      this.params.sessionId = localStorage.getItem("sessionId");

      // if (this.params.content.pageNo) {
      this.params.content.pageNo = this.pageNo + 1;
      this.pageNo += 1;
      // } else {
      //   this.params.content.pageNo = 1;
      // }



      // 请求获取新数据
      this.httpService.post("application/submit", this.params, res => {
        // 请求数据成功
        if (res.success) {
          console.log('res.sucess submit=', res);
          // 追加返回数据
          if (Array.isArray(res.data.listData) && res.data.listData.length > 0) {
            // 追加数据
            res.data.listData.map(item => {
              this.tagData.listData.push(item);
            });
          } else {
            // 没有数据了
            this.appGlobalService.showToast("没有更多商品了...", 1000, "bottom");
          }
          event.target.complete();
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
          event.target.complete();
        }
      });
    }, 500);



  }

  getInterger(value) {
    // tslint:disable-next-line:radix
    return parseInt(value);
  }
}


